package com.woniuxy.lab.woniu_lab.mqListener;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.lab.woniu_lab.exception.ExperException;
import com.woniuxy.lab.woniu_lab.model.Exper;
import com.woniuxy.lab.woniu_lab.model.Port;
import com.woniuxy.lab.woniu_lab.service.ExperService;
import com.woniuxy.lab.woniu_lab.service.PortService;
import com.woniuxy.lab.woniu_lab.service.dto.MqStopDockerComposeDto;
import com.woniuxy.lab.woniu_lab.service.dto.RmRangeDto;
import com.woniuxy.lab.woniu_lab.util.DockerUtil;
import com.woniuxy.lab.woniu_lab.util.ShellUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;

import static com.woniuxy.lab.woniu_lab.exception.WebExceptionCode.EXPER_NOT_EXIST;

/**
 * @author 17292
 */
@Component
@RocketMQMessageListener(topic = "stop_docker_compose_topic",consumerGroup = "stopDockerComPose")
@Slf4j
public class StopDockComposeListener implements RocketMQListener<MqStopDockerComposeDto> {

    public static final String CLOSE = "CLOSE";
    public static final String FAIL = "FAIL";


    @Resource
    private ExperService experService;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(MqStopDockerComposeDto mqStopDockerComposeDto) {
        log.info("收到消息并开始关闭dockCompose：{}", mqStopDockerComposeDto);
        Exper exper = experService.getById(mqStopDockerComposeDto.getId());
        //判断实验是否存在
        if(exper == null){
            log.error("实验不存在");
            return;
        }
        //判断实验是否已关闭
        if(CLOSE.equals(exper.getStatus())){
            log.error("实验已关闭");
            return;
        }
        //判断是否已到释放时间
        if (LocalDateTime.now().isBefore(exper.getReleaseTime())){
            log.info("实验未到释放时间，延时发送消息");
            LocalDateTime releaseTime = mqStopDockerComposeDto.getReleaseTime();
            mqStopDockerComposeDto.setReleaseTime(releaseTime.plusMinutes(29));
            //定时半小时关闭
            Message<MqStopDockerComposeDto> message = MessageBuilder.withPayload(mqStopDockerComposeDto).build();
            rocketMQTemplate.syncSend("stop_docker_compose_topic",message,3000,16);
            return;
        }
        //关闭实验
        experService.closeDockerCompose(FAIL);

    }
}
